package com.wealth.member.web.controller;

import iaas.redis.RedisService;
import iaas.utils.RedirectMessage;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.member.entity.Member;
import com.wealth.member.service.IMemberService;
import com.wealth.system.web.controller.BaseController;

/**
 * 个人信息设置
 * @author zjw
 */
@Controller
@RequestMapping(value="/manage/setting")
public class SettingController extends BaseController{

	Logger logger = Logger.getLogger(SettingController.class);
	
	
	@Autowired
	IMemberService memberService;
	
	@Autowired
	private RedisService redisService;
	 
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Category对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 * 
	 */
	@ModelAttribute
	public void getMember(Model model, @RequestParam(value = "id", defaultValue = "-1") Long id) {
		try{
			if (id != -1) {
				Member member = memberService.getMember(id);
				model.addAttribute("member", member);
			}
			 
		}catch(ServiceException e){
			logger.error("", e);
		}
	}
	
	
  
	@RequestMapping(value="/upPassword",method = RequestMethod.GET)
	public String passwordForm(HttpServletRequest request){
		try{
			Member member = memberService.get(memberid);
			request.setAttribute("member", member);
			request.setAttribute("password", "active");
			return "setting/upPassword";
		}catch(Exception e){
			logger.error("密码设置页面错误", e);
			return "system/500";
		}
	}
	
	@RequestMapping(value="/upPassword",method = RequestMethod.POST)
	public String updatePassword(@RequestParam(value="newPwd") String newPwd,@RequestParam(value="oldPwd") String oldPwd,RedirectAttributes redirectAttributes){
		try{
			Member temp = memberService.get(memberid);
			
			if(newPwd==null || newPwd=="" || oldPwd==null || oldPwd==""){
				
				redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipError("请填写信息"));
				return "redirect:/manage/setting/upPassword";
			}
			
			if(temp.getPassword().equals(oldPwd)){
				temp.setPassword(newPwd);
				memberService.updatePassword(temp);
				redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("密码设置操作成功"));
			}else{
				redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipError("原始密码错误"));
			}
			return "redirect:/manage/setting/upPassword";
		}catch(Exception e){
			logger.error("密码设置错误", e);
			return "system/500";
		}
	} 
	
}
